<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Category;
use App\Models\Tag;
use Illuminate\Support\Str;

class ArticleController extends Controller
{
    /**
     * 查询文章列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        // 验证参数
        $validated = $request->validate([
            'per_page' => 'integer|min:1|max:50',
            'page' => 'integer|min:1',
            'category' => 'nullable|string|max:50',
            'tags' => 'nullable|array',
            'tags.*' => 'string|max:50',
            'keyword' => 'nullable|string|max:100',
            'status' => 'nullable|in:draft,published',
            'is_top' => 'nullable|boolean',
        ]);
        
        $perPage = $validated['per_page'] ?? 10;
        
        $query = Article::query()
            ->with(['category:id,name,slug', 'tags:id,name,slug'])
            ->orderBy('is_top', 'desc')
            ->orderBy('created_at', 'desc');

        // 分类筛选
        if ($categorySlug = $validated['category'] ?? null) {
            $category = Category::where('slug', $categorySlug)->orWhere('id', $categorySlug)->first(['id']);
            if ($category) {
                $query->where('category_id', $category->id);
            }
        }

        // 标签筛选
        if ($tags = $validated['tags'] ?? null) {
            $tagIds = Tag::whereIn('slug', $tags)->pluck('id')->toArray();
            if (!empty($tagIds)) {
                $query->whereHas('tags', fn ($q) => $q->whereIn('tags.id', $tagIds));
            }
        }

        // 关键词搜索
        if ($keyword = $validated['keyword'] ?? null) {
            $keyword = trim($keyword);
            $query->where(fn ($q) =>
                $q->where('title', 'like', "%{$keyword}%")
                  ->orWhere('content', 'like', "%{$keyword}%")
                  ->orWhere('summary', 'like', "%{$keyword}%")
            );
        }

        // 状态和置顶筛选
        if ($status = $validated['status'] ?? null) {
            $query->where('status', $status);
        }
        if (isset($validated['is_top'])) {
            $query->where('is_top', $validated['is_top']);
        }

        $articles = $query->paginate($perPage, [
            'id', 'title', 'slug', 'summary', 'cover', 'user_id', 'category_id',
            'status', 'view_count', 'like_count', 'is_top', 'published_at', 'created_at'
        ]);

        return response()->json($articles, 200);
    }

    /**
     * 查询单篇文章
     *
     * @param Article $article
     * @return JsonResponse
     */
    public function show(Article $article): JsonResponse
    {
        // 如果文章未发布，则返回 404
        if ($article->status !== 'published') {
            return response()->json(['message' => '文章未发布'], 404);
        }
        
        // 预加载关联
        $article->load(['category:id,name,slug', 'tags:id,name,slug']);

        return response()->json([
            'data' => $article,
            'message' => '获取文章成功'
        ], 200);
    }

    /**
     * 创建新文章
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'summary' => 'nullable|string|max:500',
            'cover_id' => 'nullable|string|max:500',
            'category_id' => 'required|exists:categories,id',
            'tags' => 'array',
            'tags.*' => 'exists:tags,id',
            'status' => 'nullable|in:draft,published',
            'is_top' => 'nullable|boolean',
            'seo_title' => 'nullable|string|max:255',
            'seo_description' => 'nullable|string|max:500',
            'seo_keywords' => 'nullable|string|max:500',
        ]);

        $status = $validated['status'] ?? 'draft';

        $article = Article::create( array_merge($validated ,[
            // slug 的生成将由模型中的 HasUniqueSlug Trait 自动处理
            'status' => $status,
            'is_top' => $validated['is_top'] ?? false,
            'published_at' => ($status === 'published') ? now() : null,
        ]));

        $this->associateImages($article, $validated['cover_id'] ?? null);

        if (isset($validated['tags'])) {
            $article->tags()->sync($validated['tags']);
        }

        return response()->json([
            'data' => $article->load(['category', 'tags']),
            'message' => '创建文章成功',
        ], 201);
    }

    /**
     * 更新文章
     *
     * @param Request $request
     * @param Article $article
     * @return JsonResponse
     */
    public function update(Request $request, Article $article): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'summary' => 'nullable|string|max:500',
            'cover_id' => 'nullable|string|max:500',
            'category_id' => 'required|exists:categories,id',
            'tags' => 'array',
            'tags.*' => 'exists:tags,id',
            'status' => 'nullable|in:draft,published',
            'is_top' => 'nullable|boolean',
            'seo_title' => 'nullable|string|max:255',
            'seo_description' => 'nullable|string|max:500',
            'seo_keywords' => 'nullable|string|max:500',
        ]);
        
        // 如果文章状态是草稿，且请求中的状态是已发布，则更新发布时间
        if ($article->status === 'draft' && ($validated['status'] ?? null) === 'published') {
            $validated['published_at'] = now();
        }

        $article->update($validated);

        $this->associateImages($article, $validated['cover_id'] ?? null);

        // 同步标签
        if (isset($validated['tags'])) {
            $article->tags()->sync($validated['tags']);
        }

        return response()->json([
            'data' => $article->load(['category', 'tags']),
            'message' => '更新文章成功'
        ], 200);
    }

    /**
     * 删除单篇文章
     *
     * @param Article $article
     * @return JsonResponse
     */
    public function destroy(Article $article): JsonResponse
    {
        $article->tags()->detach();
        $article->delete();

        return response()->json(null, 204);
    }

    /**
     * 批量删除文章
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyBatch(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer|exists:articles,id',
        ]);

        $articles = Article::whereIn('id', $validated['ids'])->get();
        
        foreach ($articles as $article) {
             $article->tags()->detach();
             $article->delete();
        }

        return response()->json([
            'message' => '批量删除成功',
            'deleted_count' => $articles->count(),
        ], 200);
    }

    /**
     * 关联图片到文章
     */
    protected function associateImages(Article $article, $coverId = null)
    {
        // 处理封面图片
        if ($coverId) {
            $coverImage = Image::where('id', $coverId)
                ->where('user_id', auth('sanctum')->id())
                ->where('type', 'cover')
                ->where('status', 'temporary')
                ->first();
            if ($coverImage) {
                $coverImage->update([
                    'article_id' => $article->id,
                    'status' => 'permanent',
                ]);
                $article->cover = $coverImage->path;
            }
        }

        // 处理内容图片
        preg_match_all('/<img[^>]+src="([^">]+)"/i', $article->content, $matches);
        foreach ($matches[1] as $url) {
            $path = str_replace(asset('storage/'), '', $url);
            $image = Image::where('path', $path)
                ->where('user_id', auth('sanctum')->id())
                ->where('type', 'content')
                ->where('status', 'temporary')
                ->first();
            if ($image) {
                $image->update([
                    'article_id' => $article->id,
                    'status' => 'permanent',
                ]);
            }
        }
        $article->save();
    }
}
